package com.itheima.ydd.controller.client;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.common.YddUserHolder;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class HomeController {

    @Autowired
    private YddUserService yddUserService;

    @PostMapping("login")
    public ResultData login(@RequestBody YddUser yddUser){
        log.info("用户登录:{}",yddUser);

        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, yddUser.getMobile());
        queryWrapper.eq(YddUser::getPassword, DigestUtils.md5Hex(yddUser.getPassword()));
        YddUser loginUser = yddUserService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String mobile = loginUser.getMobile();

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("mobile", mobile);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

        }
        return ResultData.ok("",retMap);

    }

    @GetMapping("getUserInfo")
    public ResultData getUserInfo(){
        String mobile = YddUserHolder.getMobile();
        log.info("登录的用户为:{}",mobile);
        return ResultData.ok("","");
    }

}
